package com.example.demo.Controller;

import com.example.demo.core.JsonUtil;
import com.example.demo.core.NotFoundException;
import com.example.demo.core.Response;
import com.example.demo.core.security.JWTUtil;
import com.example.demo.model.*;
import com.example.demo.service.BookBorrowAndFeeService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/bookBorrow")
public class BookBorrowController {
    @Autowired
    BookBorrowAndFeeService bookBorrowAndFeeServiceImp;


    /**
     * 查询自己的借阅信息
     */
    @GetMapping(value = "/info/select/self")
    @RequiresAuthentication
    public Object selectSelfInfo(String bookname,
                                 @RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "20") Integer limit,HttpServletRequest request) throws NotFoundException {

        if ("".equals(bookname))
            bookname=null;

        String token=request.getHeader("Authorization");
        String name=JWTUtil.getName(token);

        List<BookBorrow> bookBorrows=bookBorrowAndFeeServiceImp.selectBorrowRecord(name,bookname);

        if(bookBorrows.size()==0)
        {
            throw new NotFoundException("查询的借阅信息为空");
        }
        return Response.okList(bookBorrows,page,limit);
    }

    /**
     * 查询所有用户的借阅信息
     */
    @GetMapping(value = "/info/select/all")
    @RequiresRoles(logical = Logical.OR,value={"default_admin","super_admin"})
    @RequiresPermissions(logical = Logical.AND,value = {"borrow:info:select:all"})
    public Object selectAllInfo(String name,String bookname,
                                 @RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "20") Integer limit,
                                 HttpServletRequest request) throws NotFoundException {

        if ("".equals(bookname))
            bookname=null;

        if ("".equals(name))
            name=null;

        List<BookBorrow> bookBorrows=bookBorrowAndFeeServiceImp.selectBorrowRecord(name,bookname);

        if(bookBorrows.size()==0)
        {
            throw new NotFoundException("查询的借阅信息为空");
        }
        return Response.okList(bookBorrows,page,limit);
    }


    /**
     * 用户第一次借书
     */
    @PostMapping(value = "/borrow")
    @RequiresAuthentication
    public Object borrowBook(@RequestBody String body,
                                 HttpServletRequest request) throws NotFoundException {
        String name = JsonUtil.parseString(body, "name");
        Integer bookinfo_id = JsonUtil.parseInteger(body, "bookinfo_id");
        Integer day = JsonUtil.parseInteger(body, "day");
        if (bookBorrowAndFeeServiceImp.bookBorrow(name,bookinfo_id,day))
            return Response.ok("借阅成功");
        return Response.fail(401,"借阅失败");
    }

    /**
     * 用户续借
     */
    @PostMapping(value = "/renew")
    @RequiresAuthentication
    public Object renewBook(@RequestBody String body,
                             HttpServletRequest request){
        Integer bookborrow_id = JsonUtil.parseInteger(body, "bookborrow_id");
        Integer day = JsonUtil.parseInteger(body, "day");

        if (bookBorrowAndFeeServiceImp.bookRenew(bookborrow_id,day))
            return Response.ok("续借成功");
        return Response.fail(401,"续借次数过多  或者  该书已经超过还书日期不允许续借");
    }



    /**
     * 用户还书
     */
    @PostMapping(value = "/return")
    @RequiresAuthentication
    public Object returnBook(@RequestBody String body,
                            HttpServletRequest request) throws NotFoundException {
        String name = JsonUtil.parseString(body, "name");
        Integer bookinfo_id = JsonUtil.parseInteger(body, "bookinfo_id");
        return Response.ok(bookBorrowAndFeeServiceImp.bookBack(name,bookinfo_id));
    }

    /**
     * 用户缴纳罚款
     */
    @PostMapping(value = "/pay")
    @RequiresAuthentication
    public Object payFee(@RequestBody String body,
                             HttpServletRequest request) throws NotFoundException {
        String name = JsonUtil.parseString(body, "name");
        Integer bookinfo_id = JsonUtil.parseInteger(body, "bookinfo_id");
        if(bookBorrowAndFeeServiceImp.feePay(name,bookinfo_id))
            return Response.ok("还款成功");
        return Response.fail(401,"还款失败");
    }

    /**
     * 用户罚款记录
     */
    @GetMapping(value = "/feeinfo/select/self")
    @RequiresPermissions(logical = Logical.AND,value = {"fee:info:select:self"})
    @RequiresAuthentication
    public Object selectSelfFeeInfo(String timePayFeeStart,String timePayFeeEnd,
                                 @RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "20") Integer limit,HttpServletRequest request) throws NotFoundException {

        String token=request.getHeader("Authorization");
        String name=JWTUtil.getName(token);

        if ("".equals(timePayFeeStart))
            timePayFeeStart=null;
        if ("".equals(timePayFeeEnd))
            timePayFeeEnd=null;

        Date timePayFeeStartDate=null,timePayFeeEndDate=null;

        try {
            if (timePayFeeStart!=null)
                timePayFeeStartDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timePayFeeStart);
            if (timePayFeeEnd!=null)
                timePayFeeEndDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timePayFeeEnd);
        } catch (Exception e) {
            return Response.fail(401,"日期格式错误");
        }

        List<FeeRecordNameMap> feeRecordList=bookBorrowAndFeeServiceImp.selectFeeRecord(name,timePayFeeStartDate,timePayFeeEndDate);

        //保留两位小数
        DecimalFormat df =new DecimalFormat("#.00");
        feeRecordList.forEach(x-> x.setFeeNeedpay(Double.parseDouble(df.format(x.getFeeNeedpay()))));

        return Response.okList(feeRecordList,page,limit);
    }

    /**
     * 所有用户罚款记录
     */
    @GetMapping(value = "/feeinfo/select/all")
    @RequiresRoles(logical = Logical.OR,value = {"default_admin","super_admin"})
    @RequiresPermissions(logical = Logical.AND,value = {"fee:info:select:all"})
    public Object selectAllFeeInfo(String name,String timePayFeeStart,String timePayFeeEnd,
                                 @RequestParam(defaultValue = "1") Integer page,
                                 @RequestParam(defaultValue = "20") Integer limit) throws NotFoundException {

        if ("".equals(name))
            name=null;
        if ("".equals(timePayFeeStart))
            timePayFeeStart=null;
        if ("".equals(timePayFeeEnd))
            timePayFeeEnd=null;

        Date timePayFeeStartDate=null,timePayFeeEndDate=null;

        try {
            if (timePayFeeStart!=null)
                timePayFeeStartDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timePayFeeStart);
            if (timePayFeeEnd!=null)
                timePayFeeEndDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(timePayFeeEnd);
        } catch (Exception e) {
            return Response.fail(401,"日期格式错误");
        }

        List<FeeRecordNameMap> feeRecordList=bookBorrowAndFeeServiceImp.selectFeeRecord(name,timePayFeeStartDate,timePayFeeEndDate);
        //保留两位小数
        DecimalFormat df =new DecimalFormat("#.00");
        feeRecordList.forEach(x-> x.setFeeNeedpay(Double.parseDouble(df.format(x.getFeeNeedpay()))));

        return Response.okList(feeRecordList,page,limit);
    }



}
